﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreEx.Common.Proxy;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
using LinFu.Proxy.Interfaces;
using LinFu.Reflection.Emit;
using Mono.Cecil;

namespace CoreEx.Database.Persistence.Implementation
{
    //[Implements(typeof(ITypeModifier), ServiceName = "AddProxyPropertiesModificator")]
    public class AddProxyPropertiesModificator : ITypeModifier, IInitialize
    {
        private IServiceContainer _serviceContainer;
        
        public void BeforeConstruction(Type originalBaseType, IEnumerable<Type> baseInterfaces, ModuleDefinition module, TypeDefinition typeDefinition)
        {
            
        }

        public void AfterConstruction(Type originalBaseType, IEnumerable<Type> baseInterfaces, ModuleDefinition module, TypeDefinition typeDefinition)
        {
            
            
            var interfaceExtractor = _serviceContainer.GetService<IExtractInterfaces>();

            HashSet<Type> interfaces = new HashSet<Type>();            
            interfaceExtractor.GetInterfaces(originalBaseType,interfaces);
            var methods = typeDefinition.Methods.Cast<MethodDefinition>();
            var propertyPicker = _serviceContainer.GetService<IPropertyPicker>();
            var targetProperties = propertyPicker.ChooseProxyPropertiesFrom(originalBaseType, interfaces);
            foreach (var targetProperty in targetProperties)
            {
                var getMethod = targetProperty.GetGetMethod();
                var setMethod = targetProperty.GetSetMethod();
                
                
                var getMethodDefinitaion = methods.Where(m => m.Name.EndsWith(getMethod.Name)).FirstOrDefault();
                MethodDefinition setMethodDefinitaion = null;
                if (setMethod != null)
                    setMethodDefinitaion = methods.Where(m => m.Name.EndsWith(setMethod.Name)).FirstOrDefault();


                

                //PropertyDefinition definition = new PropertyDefinition(targetProperty.Name, propertyTypeReference, PropertyAttributes.Unused);
                
                
                //definition.SetMethod = setMethodDefinitaion;
                //definition.GetMethod = getMethodDefinitaion;

                //typeDefinition.Properties.Add(definition);
            }

            
        }

        
        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
        }
    }
}
